package com.zhisuo.apicenter.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhisuo.apicenter.model.*;
import com.zhisuo.apicenter.service.ApiService;
import com.zhisuo.apicenter.service.CarApiService;
import com.zhisuo.apicenter.service.ExpressManService;
import com.zhisuo.apicenter.service.UserManService;
import com.zhisuo.apicenter.util.SendSmsUtil;
import com.zhisuo.apicenter.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/carapi")
public class CarApiController {

    private static final Logger log = LoggerFactory.getLogger(CarApiController.class);

    private CarApiService carApiService;

    @Autowired
    public void setApiService(CarApiService carApiService) {
        this.carApiService = carApiService;
    }


    private ExpressManService expressManService;

    @Autowired
    public void setExpressManService(ExpressManService expressManService) {
        this.expressManService = expressManService;
    }

    private UserManService userManService;

    @Autowired
    public void setUserManService(UserManService userManService) {
        this.userManService = userManService;
    }

    private ApiService apiService;

    @Autowired
    public void setApiService(ApiService apiService) {
        this.apiService = apiService;
    }


    /**
     * 上传车辆VPN地址
     */
    @RequestMapping(value = "/submitCarVpn")
    public void submitCarVpn(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        //log.info("submitCarRegister-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }

        JSONObject jsonObject = JSONObject.parseObject(str);

        String vin = jsonObject.getString("vin");
        if (StringUtils.isEmpty(vin)) {
            responseErrorData("car vin is empty", resp);
            return;
        }

        ZhiSuoCar car = expressManService.getCarBySn(vin);

        if (car == null) {
            responseErrorData("car is empty", resp);
            return;
        }

        String vpnip=jsonObject.getString("vpnip");
        String frontport=jsonObject.getString("frontport");
        String backport=jsonObject.getString("backport");
        String leftport=jsonObject.getString("leftport");
        String rightport=jsonObject.getString("rightport");

        carApiService.updateVpnInfoByCarID(car.getId(),vpnip,frontport,backport,leftport,rightport);

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "上传成功");
        responseData(resultObj.toString(), resp);
    }



    /**
     * t-box注册指令
     */
    @RequestMapping(value = "/submitCarRegister")
    public void submitCarRegister(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        //log.info("submitCarRegister-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }

        JSONObject jsonObject = JSONObject.parseObject(str);

        String vin = jsonObject.getString("vin");
        if (StringUtils.isEmpty(vin)) {
            responseErrorData("car vin is empty", resp);
            return;
        }

        ZhiSuoCar car = expressManService.getCarBySn(vin);

        if (car == null) {
            responseErrorData("car is empty", resp);
            return;
        }

        JSONObject allboxjson = jsonObject.getJSONObject("boxinfo");
        String boxnum = allboxjson.getString("boxnum");
        String leftbox = allboxjson.getString("leftbox");
        String rightbox = allboxjson.getString("rightbox");
        //1一个柜子只能一个订单 2一个柜子支持多订单
        String openattr = allboxjson.getString("openattr");
        if (StringUtil.isEmpty(boxnum)) {
            boxnum = "0";
        }
        if (StringUtil.isEmpty(leftbox)) {
            leftbox = "0";
        }
        if (StringUtil.isEmpty(rightbox)) {
            rightbox = "0";
        }
        carApiService.updateCarInfoByVin(vin, boxnum, leftbox, rightbox,openattr);

        JSONArray boxload = allboxjson.getJSONArray("box");
        JSONObject boxjson = null;
        if (boxload.size() > 0 && boxload != null) {

            //ZhiSuoCar car=expressManService.getCarBySn(vin);
            for (int i = 0; i < boxload.size(); i++) {
                boxjson = boxload.getJSONObject(i);
                String boxname = boxjson.getString("name");
                //right left
                String pos = boxjson.getString("pos");
                //1,2,3,4,5
                String size = boxjson.getString("size");

                String boxid = carApiService.getBoxIdByNameAndVin(boxname, car.getId() + "");
                if (StringUtils.isEmpty(boxid)) {
                    //插入
                    carApiService.insertNewCarBoxInfo(boxname, pos, size, vin, car.getId() + "");
                } else {
                    //更新
                    carApiService.updateCarBoxInfo(boxid, pos, size);
                }
            }


        } else {
            responseErrorData("car vin is empty", resp);
            return;
        }


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "上传成功");
        responseData(resultObj.toString(), resp);
    }

    /**
     * t-box心跳指令 heart
     */
    @RequestMapping(value = "/submitCarHeart")
    public void submitCarHeart(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        //log.info("submitCarHeart-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }


        JSONObject jsonObject = JSONObject.parseObject(str);
        //System.out.println("submitCarHeart----jsonObject---" + jsonObject);
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "上传成功");
        responseData(resultObj.toString(), resp);
    }

    /**
     * 2.2.1.车辆状态 车端定时向云端上报车辆状态，上报频率6s一次。
     *
     * @param req
     * @param resp
     * @throws Exception 检查
     *                   <p>
     *                   {"name":"vehicleinfo","vin":"",
     *                   "id":"461107cc-1e94-4ba2-a71b-e0b925139db8","timestamp":"2020-10-09 19:05:13","seq":"1","version":"1.0",
     *                   "vehicleinfo":{"status":"","errorcode":"0","position":{"stop":"","lon":"0.000000","lat":"0.000000","heading":"90.0"},
     *                   "speed":{"value":"0.0","unit":"km/h"},
     *                   "battery":{"soc":"0","range":{"value":"0","unit":"km"},"power":{"value":"0.0","unit":"kw"}}}}
     *                   status: 1-rolling（自动驾驶程序运行中，车速可能为0）; 2-parking（到站）; 3-charging（充电）。
     *                   errorcode: 错误代码 （常见场景：0-正常；1-拥堵、2-车门未关、3-系统内部故障 ）
     *                   position:  站点名（parking时为站点名称，rolling时为空），纬度，经度，车头朝向 （主要用于地图展现）。
     *                   speed: 速度、速度单位；
     *                   battery: soc荷电状态（剩余容量），车程（数量、车程单位）， 功率（数量、功率单位）
     *
     *                   //            String beforestop = positionjson.getString("beforestop");
     * //            String beforestop = "";
     * //
     * //            if (StringUtil.isNotEmpty(beforestop)) {
     * //
     * //                System.out.println("beforestop-----"+beforestop);
     * //                if(!stop.equals(car.getHomestation())){
     * //                    //设置超时未取发送短信
     * //                    List<DeliveryOrder> listNoDeliveryOrder = userManService.getListNoDeliveryOrderBySync(car.getId() + "", beforestop);
     * //                    System.out.println("listNoDeliveryOrder-----"+listNoDeliveryOrder.size());
     * //                    if (listNoDeliveryOrder != null && listNoDeliveryOrder.size() > 0) {
     * //
     * //                        for (DeliveryOrder order : listNoDeliveryOrder) {
     * //
     * //                            //短信通知重新预约，订单状态变更为待预约
     * //                            //【智梭无人车】亲爱的小主,您的快件没有在预约时间内领取，请打开微信小程序，搜索智梭无人车，重新预约哟~
     * //
     * //                            userManService.insertNewZhiSuoCarNextStopSms("", order.getReceiptusermobile(), order.getCarid() + "", 3);
     * //
     * //                            //将订单状态改变
     * //                            userManService.updateOrderStatusAgainOrderByOrderId(order.getId());
     * //                            if(order.getOrdertype()==1){
     * //                                //只有零售端才下发商家短信
     * //                                String sellermobile=userManService.getMobilByUserId(order.getUserid()+"");
     * //                                userManService.insertNewZhiSuoCarNextStopSms(order.getCreate_time()+","+order.getReceiptusermobile(),sellermobile , order.getCarid() + "", 4);
     * //
     * //                            }
     * //
     * //
     * //                        }
     * //                    }
     * //                }
     * //
     * //            }
     */
    @RequestMapping(value = "/submitCarStatus")
    public void submitCarStatus(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
//        LogFactory.getLog(this.getClass()).info("getNoDeliveryOrderByStop-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }


        JSONObject jsonObject = JSONObject.parseObject(str);


        ZhiSuoCarStatus carstatus = new ZhiSuoCarStatus();


        String vin = jsonObject.getString("vin");
        if (StringUtils.isEmpty(vin)) {
            responseErrorData("car vin is empty", resp);
            return;
        }

        String name = jsonObject.getString("name");

//        String seq=jsonObject.getString("seq");
//        String id=jsonObject.getString("id");

        String timestamp = jsonObject.getString("timestamp");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = formatter.parse(timestamp);

        JSONObject vehicleinfojson = jsonObject.getJSONObject("vehicleinfo");

        //status: 1-rolling（自动驾驶程序运行中，车速可能为0）; 2-parking（到站）; 3-charging（充电）。
        String status = vehicleinfojson.getString("status");


        //errorcode: 错误代码 （常见场景：0-正常；1-拥堵、2-车门未关、3-系统内部故障 ）
        String errorcode = vehicleinfojson.getString("errorcode");


        //position:  站点名（parking时为站点名称，rolling时为空），纬度，经度，车头朝向 （主要用于地图展现）
        JSONObject positionjson = vehicleinfojson.getJSONObject("position");
        String stop = positionjson.getString("stop");
        if (status.equals("2")) {




            //根据vin查找车，将到站点置为1
            ZhiSuoCar car = expressManService.getCarBySn(vin);

            if (car == null) {
                responseErrorData("car is empty", resp);
                return;
            }

            //垃圾车处理
            if(car.getType()==3){
                //将站点垃圾都置为已收取
                expressManService.updateCarStatusByCaridAndAddressCode(car.getId(),stop);
            }

            //车辆到站，状态置为1
            expressManService.updateCarStopListStatus(car.getId(), stop);


            //查找下一站指令
            String nextstop = userManService.getNextStopByCarId(car.getId());


            if (StringUtil.isEmpty(nextstop)) {

                //返回起始点，或者已在起始点
                if(!stop.equals(car.getHomestation())){
                    //倒数一站
                    //select stoptcp from zhisuo_car_nextstoplist where carid=? and nextstop=? and status=0
                    //String stoptcp = expressManService.getStopTcpStatusByCarIdAndStop(car.getId(), car.getHomestation());
                    //select id from zhisuo_car_nextstoptcp where carid=? and stop=? and status=0
                    String stoptcp=userManService.getNextStopTcpIdByCarIdAndStop(car.getId(), car.getHomestation());

                    if (StringUtil.isEmpty(stoptcp)) {
                        String stop_timeout_sec=apiService.getTcpUrlByTcpCenterUrl("stop_timeout_sec");

                        userManService.insertNewZhiSuoCarNextStopTcp(car.getSn(), car.getId(), car.getName(), car.getHomestation(),stop_timeout_sec,stop);

                        System.out.println("submitCarStatus333333----jsonObject---vin--"+car.getSn()+"--stop----"+car.getHomestation()+"---"+new Date());
                    }
                }




            } else {
                //有下一站的站点，下一站命令是否已经在库中

                //String stoptcp = expressManService.getStopTcpStatusByCarIdAndStop(car.getId(), nextstop);

                String stoptcp=userManService.getNextStopTcpIdByCarIdAndStop(car.getId(), nextstop);


                List<String> listhasbox=userManService.getListHasBoxByCarId(car.getId(),stop);
                if(StringUtil.isEmpty(stoptcp)){


                    if(stop.equals( car.getHomestation())){
                        userManService.insertNewZhiSuoCarSendNextStopTcp(car.getSn(),car.getId(),car.getName(),nextstop,stop);
                        System.out.println("submitCarStatus11111----jsonObject---vin--"+car.getSn()+"--stop----"+nextstop+"---"+new Date());


                    }else{
                        String stop_timeout_sec=apiService.getTcpUrlByTcpCenterUrl("stop_timeout_sec");
                        userManService.insertNewZhiSuoCarNextStopTcp(car.getSn(), car.getId(), car.getName(), nextstop,stop_timeout_sec,stop);
                        System.out.println("submitCarStatus22222----jsonObject---vin--"+car.getSn()+"--stop----"+nextstop+"---"+new Date());

//                        if(listhasbox!= null && listhasbox.size()==0){
//                            userManService.insertNewZhiSuoCarSendNextStopTcp(car.getSn(),car.getId(),car.getName(),nextstop,stop);
//                        }

                    }
                    //expressManService.updateCarStopTcpStatus(car.getId(), nextstop);






                    //发件车的
                    List<DeliveryOrder> listNextStopDeliveryOrder = expressManService.getListNextDeliveryOrderByNextStop(nextstop, car.getId() + "");

                    if (listNextStopDeliveryOrder != null && listNextStopDeliveryOrder.size() > 0) {
                        for (DeliveryOrder nextorder : listNextStopDeliveryOrder) {
                            String smsstatus = userManService.getSmsStatusByCaridMobile(nextorder.getReceiptcode(), nextorder.getReceiptusermobile(), nextorder.getCarid() + "");

                            if (StringUtil.isEmpty(smsstatus)) {
                                userManService.insertNewZhiSuoCarNextStopSms(nextorder.getReceiptcode(), nextorder.getReceiptusermobile(), nextorder.getCarid() + "", 0);
                                //语音短信
                                userManService.insertNewZhiSuoCarNextStopSms("5,"+nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",5);
                            }


                        }
                    }


                    //根据下一站指令，获取下一个用户  收件车的
                    List<SendOrder> listNextSendOrder=expressManService.getListNextSendOrderByNextStop(nextstop,car.getId()+"");



                    if(listNextSendOrder != null && listNextSendOrder.size()>0){
                        for(SendOrder nextorder:listNextSendOrder){
                            String[] params = new String[]{nextorder.getSendcode()};
                            String[] phoneNumbers =new String[]{nextorder.getSendmobile()};
                            //发送短信
                            SendSmsUtil.sendSmsGetBox(params,phoneNumbers);
                            userManService.insertNewZhiSuoCarNextStopSms(nextorder.getSendcode(),nextorder.getSendmobile(),nextorder.getCarid()+"",0);
                            //订单状态置为1
                            userManService.updateSendOrderStatusByOrderId(nextorder.getId());
                        }
                    }



                }
//                if (StringUtil.isNotEmpty(stoptcp)) {
//                    if (Integer.parseInt(stoptcp) == 0) {
//
//
//
//                    }
//
//
//                }


            }





        }
        String lon = positionjson.getString("lon");
        String lat = positionjson.getString("lat");
        String heading = positionjson.getString("heading");


        //速度、速度单位；
        JSONObject speedjson = vehicleinfojson.getJSONObject("speed");
        String speedvalue = speedjson.getString("value");
        String speedunit = speedjson.getString("unit");


        //battery: soc荷电状态（剩余容量），车程（数量、车程单位）， 功率（数量、功率单位）
        JSONObject batteryjson = vehicleinfojson.getJSONObject("battery");
        String soc = batteryjson.getString("soc");
        JSONObject batteryrangejson = batteryjson.getJSONObject("range");
        String rangevalue = batteryrangejson.getString("value");
        String rangeunit = batteryrangejson.getString("unit");
        JSONObject batterpowerjson = batteryjson.getJSONObject("power");
        String powervalue = batterpowerjson.getString("value");
        String powerunit = batterpowerjson.getString("unit");


        //距离状态：
        JSONObject distancejson = vehicleinfojson.getJSONObject("distance");
        JSONObject distancetotaljson = distancejson.getJSONObject("total");
        String distancetotal = distancetotaljson.getString("range");
        JSONObject distanceremainjson = distancejson.getJSONObject("remain");
        String remaintotal = distanceremainjson.getString("range");


        carstatus.setDistancetotal(distancetotal);
        carstatus.setRemaintotal(remaintotal);
        carstatus.setVin(vin);
        carstatus.setName(name);
        carstatus.setUpdate_time(date);
        carstatus.setVehicleinfostatus(status);
        carstatus.setVehicleinfoerrorcode(errorcode);
        carstatus.setPositionstop(stop);
        carstatus.setPositionlon(lon);
        carstatus.setPositionlat(lat);
        carstatus.setPositionheading(heading);
        carstatus.setSpeedunit(speedunit);
        carstatus.setSpeedvalue(speedvalue);
        carstatus.setBatterysoc(soc);
        carstatus.setBatteryrangevalue(rangevalue);
        carstatus.setBatteryrangeunit(rangeunit);
        carstatus.setBatterypowerunit(powerunit);
        carstatus.setBatterypowervalue(powervalue);

        carApiService.insertNewCarStatus(carstatus);
        //System.out.println("submitCarStatus----jsonObject---"+vin+"--"+date);
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "上传成功");
        responseData(resultObj.toString(), resp);
    }


    /**
     * 2.2.2.载物状态 车端定时向云端上报柜子载物状态，上报频率6s一次。
     *
     * @param req
     * @param resp
     * @throws Exception 检查
     *                   <p>
     *                   {"boxload":[{"name":"box1","value":"0"},{"name":"box2","value":"0"},{"name":"box3","value":"0"},{"name":"box4","value":"0"},
     *                   {"name":"box5","value":"0"},{"name":"box6","value":"0"},{"name":"box7","value":"0"},{"name":"box8","value":"0"},{"name":"box9","value":"0"},
     *                   {"name":"box10","value":"0"},{"name":"box11","value":"0"},{"name":"box12","value":"0"},
     *                   {"name":"box13","value":"0"},{"name":"box14","value":"0"},{"name":"box15","value":"0"},
     *                   {"name":"box16","value":"0"},{"name":"box17","value":"0"},{"name":"box18","value":"0"},
     *                   {"name":"box19","value":"0"},{"name":"box20","value":"0"},{"name":"box21","value":"0"},
     *                   {"name":"box22","value":"0"},{"name":"box23","value":"0"},{"name":"box24","value":"0"}],
     *                   "id":"e9bd7c77-cda5-4563-9502-a1b2897a8721",
     *                   "name":"boxloadstatus","seq":"1","timestamp":"2020-10-09 19:05:15","version":"1.0","vin":""}
     *                   <p>
     *                   boxload status：
     *                   0：无货
     *                   1：有货
     *                   2：异常
     */
    @RequestMapping(value = "/submitCarBoxLoadStatus")
    public void submitCarBoxLoadStatus(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        //log.info("submitCarBoxLoadStatus-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }


        JSONObject jsonObject = JSONObject.parseObject(str);
        //System.out.println("submitCarBoxLoadStatus----jsonObject---"+jsonObject);

        String vin = jsonObject.getString("vin");
        if (StringUtils.isEmpty(vin)) {
            responseErrorData("car vin is empty", resp);
            return;
        }
        JSONArray boxload = jsonObject.getJSONArray("boxload");
        JSONObject boxjson = null;
        if (boxload.size() > 0 && boxload != null) {

            ZhiSuoCar car = expressManService.getCarBySn(vin);
            if (car == null) {
                responseErrorData("car is empty", resp);
                return;
            }
            for (int i = 0; i < boxload.size(); i++) {
                boxjson = boxload.getJSONObject(i);
                String boxname = boxjson.getString("name");
                //0无货 1有货，2异常
                String boxvalue = boxjson.getString("value");

                String boxid = carApiService.getBoxIdByNameAndVin(boxname, car.getId() + "");
                if (StringUtils.isEmpty(boxid)) {
                    //插入
                    carApiService.insertNewCarBox(boxname, boxvalue, vin, car.getId() + "");
                } else {
                    //更新
                    carApiService.updateCarBoxStatus(boxid, boxvalue);
                }
            }


        } else {
            responseErrorData("car vin is empty", resp);
            return;
        }


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "上传成功");
        responseData(resultObj.toString(), resp);
    }


    /**
     * 2.2.2.门锁状态 车端定时向云端上报柜子门锁状态，上报频率6s一次
     *
     * @param req
     * @param resp {"boxdoor":[{"name":"box1","value":"0"},{"name":"box2","value":"0"},{"name":"box3","value":"0"},
     *             {"name":"box4","value":"0"},{"name":"box5","value":"0"},{"name":"box6","value":"0"},{"name":"box7","value":"0"},
     *             {"name":"box8","value":"0"},{"name":"box9","value":"0"},{"name":"box10","value":"0"},{"name":"box11","value":"0"},
     *             {"name":"box12","value":"0"},{"name":"box13","value":"0"},{"name":"box14","value":"0"},{"name":"box15","value":"0"},
     *             {"name":"box16","value":"0"},{"name":"box17","value":"0"},{"name":"box18","value":"0"},{"name":"box19","value":"0"},
     *             {"name":"box20","value":"0"},{"name":"box21","value":"0"},{"name":"box22","value":"0"},{"name":"box23","value":"0"},
     *             {"name":"box24","value":"0"}],
     *             "id":"092da855-7075-4d2e-95c5-283183c6637f",
     *             "name":"boxdoorstatus","seq":"1","timestamp":"2020-10-09 19:05:17","version":"1.0","vin":""}
     * @throws Exception 检查
     *                   <p>
     *                   boxdoor status：
     *                   0：关门状态
     *                   1：开门状态
     *                   2：异常
     */
    @RequestMapping(value = "/submitCarBoxDoorStatus")
    public void submitCarBoxDoorStatus(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        //log.info("submitCarBoxDoorStatus-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }


        JSONObject jsonObject = JSONObject.parseObject(str);
        //System.out.println("submitCarBoxDoorStatus----jsonObject---"+jsonObject);


        String vin = jsonObject.getString("vin");
        if (StringUtils.isEmpty(vin)) {
            responseErrorData("car vin is empty", resp);
            return;
        }
        JSONArray boxdoor = jsonObject.getJSONArray("boxdoor");
        JSONObject boxjson = null;
        ZhiSuoCar car = expressManService.getCarBySn(vin);
        if (car == null) {
            responseErrorData("car is empty", resp);
            return;
        }

        if (boxdoor.size() > 0 && boxdoor != null) {
            for (int i = 0; i < boxdoor.size(); i++) {
                boxjson = boxdoor.getJSONObject(i);
                String boxname = boxjson.getString("name");
                //0无货 1有货，2异常
                String boxvalue = boxjson.getString("value");

                String boxid = carApiService.getBoxIdByNameAndVin(boxname, car.getId() + "");
                if (StringUtils.isEmpty(boxid)) {
                    //插入
                    carApiService.insertNewCarBoxDoor(boxname, boxvalue, vin, car.getId() + "");
                } else {
                    //更新
                    carApiService.updateCarBoxDoorStatus(boxid, boxvalue);
                }
            }


        } else {
            responseErrorData("car vin is empty", resp);
            return;
        }


        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "上传成功");
        responseData(resultObj.toString(), resp);
    }


    /**
     * 从req中读取数据
     *
     * @param req
     * @return
     */
    private String getRequestBodyString(HttpServletRequest req) {
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            // e.printStackTrace();
            return null;
        }
        return builder.toString();
    }

    private void responseErrorData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        JSONObject resultObj = new JSONObject();
        resultObj.put("error_code", 1);
        resultObj.put("error_msg", string);
        responseData(resultObj.toString(), resp);
    }

    private void responseData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        responseDate("application/json;charset=UTF-8", string, resp);

    }

    private void responseDate(String contentType, String value, HttpServletResponse resp) throws Exception {
        resp.setContentType(contentType);
        resp.getWriter().write(value);
    }
}
